require 'net/http'
require 'uri'

module SmsOmf
    # This class is used to send a SMS to an array of destinations.
  # A Movistar number and its associated 770 password are mandatory
  class SmsSender
   
     URL = 'https://opensms.movistar.es/aplicacionpost/loginEnvio.jsp'
   
    
    # Class constructor
    # @login Movistar phone number
    # @password 770 password
    def initialize(login = nil, password=nil)
      @login = login.to_s unless login.nil?
      @password = password.to_s unless password.nil?
    end
   
     def send(destinations, message)
       if (@login.nil? or @password.nil?)
         raise "login and password are not allowd to be nil"
       end
       unless destinations.nil?
         if destinations.respond_to?("map!")
           destinations.map!{|item| item.to_s.strip }
         end
         if destinations.respond_to?("join")
           numbers = destinations.join(";")
         else
           numbers = destinations.to_s
         end
       else
         raise "Null destinations not allowed"
       end
       return if numbers.empty?
       response = Net::HTTP.post_form(URI.parse(URL),
         {
           'TM_ACTION' => 'AUTHENTICATE',
           'TM_LOGIN' => @login,
           'TM_PASSWORD' => @password,
           'to' => numbers,
           'message' => message
         }
       )
       puts response.body
       raise "SMS could not be sent: #{response.body}" unless response.body =~ /OK/
       puts "SMS has been sent correctly"
     end
  end

end

